home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / csv.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  13KB  |  435 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. csv.py - read/write/investigate CSV files
  6. '''
  7. import re
  8. from functools import reduce
  9. from _csv import Error, __version__, writer, reader, register_dialect, unregister_dialect, get_dialect, list_dialects, field_size_limit, QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE, __doc__
  10. from _csv import Dialect as _Dialect
  11.  
  12. try:
  13.     from cStringIO import StringIO
  14. except ImportError:
  15.     from StringIO import StringIO
  16.  
  17. __all__ = [
  18.     'QUOTE_MINIMAL',
  19.     'QUOTE_ALL',
  20.     'QUOTE_NONNUMERIC',
  21.     'QUOTE_NONE',
  22.     'Error',
  23.     'Dialect',
  24.     '__doc__',
  25.     'excel',
  26.     'excel_tab',
  27.     'field_size_limit',
  28.     'reader',
  29.     'writer',
  30.     'register_dialect',
  31.     'get_dialect',
  32.     'list_dialects',
  33.     'Sniffer',
  34.     'unregister_dialect',
  35.     '__version__',
  36.     'DictReader',
  37.     'DictWriter']
  38.  
  39. class Dialect:
  40.     '''Describe an Excel dialect.
  41.  
  42.     This must be subclassed (see csv.excel).  Valid attributes are:
  43.     delimiter, quotechar, escapechar, doublequote, skipinitialspace,
  44.     lineterminator, quoting.
  45.  
  46.     '''
  47.     _name = ''
  48.     _valid = False
  49.     delimiter = None
  50.     quotechar = None
  51.     escapechar = None
  52.     doublequote = None
  53.     skipinitialspace = None
  54.     lineterminator = None
  55.     quoting = None
  56.     
  57.     def __init__(self):
  58.         if self.__class__ != Dialect:
  59.             self._valid = True
  60.         
  61.         self._validate()
  62.  
  63.     
  64.     def _validate(self):
  65.         
  66.         try:
  67.             _Dialect(self)
  68.         except TypeError:
  69.             e = None
  70.             raise Error(str(e))
  71.  
  72.  
  73.  
  74.  
  75. class excel(Dialect):
  76.     '''Describe the usual properties of Excel-generated CSV files.'''
  77.     delimiter = ','
  78.     quotechar = '"'
  79.     doublequote = True
  80.     skipinitialspace = False
  81.     lineterminator = '\r\n'
  82.     quoting = QUOTE_MINIMAL
  83.  
  84. register_dialect('excel', excel)
  85.  
  86. class excel_tab(excel):
  87.     '''Describe the usual properties of Excel-generated TAB-delimited files.'''
  88.     delimiter = '\t'
  89.  
  90. register_dialect('excel-tab', excel_tab)
  91.  
  92. class DictReader:
  93.     
  94.     def __init__(self, f, fieldnames = None, restkey = None, restval = None, dialect = 'excel', *args, **kwds):
  95.         self._fieldnames = fieldnames
  96.         self.restkey = restkey
  97.         self.restval = restval
  98.         self.reader = reader(f, dialect, *args, **kwds)
  99.         self.dialect = dialect
  100.         self.line_num = 0
  101.  
  102.     
  103.     def __iter__(self):
  104.         return self
  105.  
  106.     
  107.     def fieldnames(self):
  108.         if self._fieldnames is None:
  109.             
  110.             try:
  111.                 self._fieldnames = self.reader.next()
  112.             except StopIteration:
  113.                 pass
  114.             except:
  115.                 None<EXCEPTION MATCH>StopIteration
  116.             
  117.  
  118.         None<EXCEPTION MATCH>StopIteration
  119.         self.line_num = self.reader.line_num
  120.         return self._fieldnames
  121.  
  122.     fieldnames = property(fieldnames)
  123.     
  124.     def fieldnames(self, value):
  125.         self._fieldnames = value
  126.  
  127.     fieldnames = fieldnames.setter(fieldnames)
  128.     
  129.     def next(self):
  130.         if self.line_num == 0:
  131.             self.fieldnames
  132.         
  133.         row = self.reader.next()
  134.         self.line_num = self.reader.line_num
  135.         while row == []:
  136.             row = self.reader.next()
  137.         d = dict(zip(self.fieldnames, row))
  138.         lf = len(self.fieldnames)
  139.         lr = len(row)
  140.         if lf < lr:
  141.             d[self.restkey] = row[lf:]
  142.         elif lf > lr:
  143.             for key in self.fieldnames[lr:]:
  144.                 d[key] = self.restval
  145.             
  146.         
  147.         return d
  148.  
  149.  
  150.  
  151. class DictWriter:
  152.     
  153.     def __init__(self, f, fieldnames, restval = '', extrasaction = 'raise', dialect = 'excel', *args, **kwds):
  154.         self.fieldnames = fieldnames
  155.         self.restval = restval
  156.         if extrasaction.lower() not in ('raise', 'ignore'):
  157.             raise ValueError, "extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction
  158.         extrasaction.lower() not in ('raise', 'ignore')
  159.         self.extrasaction = extrasaction
  160.         self.writer = writer(f, dialect, *args, **kwds)
  161.  
  162.     
  163.     def _dict_to_list(self, rowdict):
  164.         return [ rowdict.get(key, self.restval) for key in self.fieldnames ]
  165.  
  166.     
  167.     def writerow(self, rowdict):
  168.         return self.writer.writerow(self._dict_to_list(rowdict))
  169.  
  170.     
  171.     def writerows(self, rowdicts):
  172.         rows = []
  173.         for rowdict in rowdicts:
  174.             rows.append(self._dict_to_list(rowdict))
  175.         
  176.         return self.writer.writerows(rows)
  177.  
  178.  
  179.  
  180. try:
  181.     complex
  182. except NameError:
  183.     complex = float
  184.  
  185.  
  186. class Sniffer:
  187.     '''
  188.     "Sniffs" the format of a CSV file (i.e. delimiter, quotechar)
  189.     Returns a Dialect object.
  190.     '''
  191.     
  192.     def __init__(self):
  193.         self.preferred = [
  194.             ',',
  195.             '\t',
  196.             ';',
  197.             ' ',
  198.             ':']
  199.  
  200.     
  201.     def sniff(self, sample, delimiters = None):
  202.         '''
  203.         Returns a dialect (or None) corresponding to the sample
  204.         '''
  205.         (quotechar, delimiter, skipinitialspace) = self._guess_quote_and_delimiter(sample, delimiters)
  206.         if not delimiter:
  207.             (delimiter, skipinitialspace) = self._guess_delimiter(sample, delimiters)
  208.         
  209.         if not delimiter:
  210.             raise Error, 'Could not determine delimiter'
  211.         delimiter
  212.         
  213.         class dialect(Dialect):
  214.             _name = 'sniffed'
  215.             lineterminator = '\r\n'
  216.             quoting = QUOTE_MINIMAL
  217.             doublequote = False
  218.  
  219.         dialect.delimiter = delimiter
  220.         if not quotechar:
  221.             pass
  222.         dialect.quotechar = '"'
  223.         dialect.skipinitialspace = skipinitialspace
  224.         return dialect
  225.  
  226.     
  227.     def _guess_quote_and_delimiter(self, data, delimiters):
  228.         """
  229.         Looks for text enclosed between two identical quotes
  230.         (the probable quotechar) which are preceded and followed
  231.         by the same character (the probable delimiter).
  232.         For example:
  233.                          ,'some text',
  234.         The quote with the most wins, same with the delimiter.
  235.         If there is no quotechar the delimiter can't be determined
  236.         this way.
  237.         """
  238.         matches = []
  239.         for restr in ('(?P<delim>[^\\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\\w\n"\'])(?P<space> ?)', '(?P<delim>>[^\\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'):
  240.             regexp = re.compile(restr, re.DOTALL | re.MULTILINE)
  241.             matches = regexp.findall(data)
  242.             if matches:
  243.                 break
  244.                 continue
  245.         
  246.         if not matches:
  247.             return ('', None, 0)
  248.         quotes = { }
  249.         delims = { }
  250.         spaces = 0
  251.         for m in matches:
  252.             n = regexp.groupindex['quote'] - 1
  253.             key = m[n]
  254.             if key:
  255.                 quotes[key] = quotes.get(key, 0) + 1
  256.             
  257.             
  258.             try:
  259.                 n = regexp.groupindex['delim'] - 1
  260.                 key = m[n]
  261.             except KeyError:
  262.                 continue
  263.  
  264.             if key:
  265.                 if delimiters is None or key in delimiters:
  266.                     delims[key] = delims.get(key, 0) + 1
  267.                 
  268.             
  269.             try:
  270.                 n = regexp.groupindex['space'] - 1
  271.             except KeyError:
  272.                 continue
  273.  
  274.             if m[n]:
  275.                 spaces += 1
  276.                 continue
  277.         
  278.         quotechar = reduce((lambda a, b, quotes = quotes: if not quotes[a] > quotes[b] or a:
  279. passb), quotes.keys())
  280.         if delims:
  281.             delim = reduce((lambda a, b, delims = delims: if not delims[a] > delims[b] or a:
  282. passb), delims.keys())
  283.             skipinitialspace = delims[delim] == spaces
  284.             if delim == '\n':
  285.                 delim = ''
  286.             
  287.         else:
  288.             delim = ''
  289.             skipinitialspace = 0
  290.         return (quotechar, delim, skipinitialspace)
  291.  
  292.     
  293.     def _guess_delimiter(self, data, delimiters):
  294.         """
  295.         The delimiter /should/ occur the same number of times on
  296.         each row. However, due to malformed data, it may not. We don't want
  297.         an all or nothing approach, so we allow for small variations in this
  298.         number.
  299.           1) build a table of the frequency of each character on every line.
  300.           2) build a table of freqencies of this frequency (meta-frequency?),
  301.              e.g.  'x occurred 5 times in 10 rows, 6 times in 1000 rows,
  302.              7 times in 2 rows'
  303.           3) use the mode of the meta-frequency to determine the /expected/
  304.              frequency for that character
  305.           4) find out how often the character actually meets that goal
  306.           5) the character that best meets its goal is the delimiter
  307.         For performance reasons, the data is evaluated in chunks, so it can
  308.         try and evaluate the smallest portion of the data possible, evaluating
  309.         additional chunks as necessary.
  310.         """
  311.         data = filter(None, data.split('\n'))
  312.         ascii = [ chr(c) for c in range(127) ]
  313.         chunkLength = min(10, len(data))
  314.         iteration = 0
  315.         charFrequency = { }
  316.         modes = { }
  317.         delims = { }
  318.         start = 0
  319.         end = min(chunkLength, len(data))
  320.         while start < len(data):
  321.             iteration += 1
  322.             for line in data[start:end]:
  323.                 for char in ascii:
  324.                     metaFrequency = charFrequency.get(char, { })
  325.                     freq = line.count(char)
  326.                     metaFrequency[freq] = metaFrequency.get(freq, 0) + 1
  327.                     charFrequency[char] = metaFrequency
  328.                 
  329.             
  330.             for char in charFrequency.keys():
  331.                 items = charFrequency[char].items()
  332.                 if len(items) > 1:
  333.                     modes[char] = reduce((lambda a, b: if not a[1] > b[1] or a:
  334. passb), items)
  335.                     items.remove(modes[char])
  336.                     modes[char] = (modes[char][0], modes[char][1] - reduce((lambda a, b: (0, a[1] + b[1])), items)[1])
  337.                     continue
  338.                 None if len(items) == 1 and items[0][0] == 0 else []
  339.                 modes[char] = items[0]
  340.             
  341.             modeList = modes.items()
  342.             total = float(chunkLength * iteration)
  343.             consistency = 1
  344.             threshold = 0.9
  345.             while len(delims) == 0 and consistency >= threshold:
  346.                 for k, v in modeList:
  347.                     if v[0] > 0 and v[1] > 0:
  348.                         if v[1] / total >= consistency:
  349.                             pass
  350.                         None if delimiters is None or k in delimiters else k in delimiters
  351.                         continue
  352.                 
  353.                 consistency -= 0.01
  354.             if len(delims) == 1:
  355.                 delim = delims.keys()[0]
  356.                 skipinitialspace = data[0].count(delim) == data[0].count('%c ' % delim)
  357.                 return (delim, skipinitialspace)
  358.             start = end
  359.             end += chunkLength
  360.             continue
  361.             len(delims) == 1
  362.         if not delims:
  363.             return ('', 0)
  364.         items = [ (v, k) for k, v in delims.items() ]
  365.         items.sort()
  366.         delim = items[-1][1]
  367.         skipinitialspace = data[0].count(delim) == data[0].count('%c ' % delim)
  368.         return (delim, skipinitialspace)
  369.  
  370.     
  371.     def has_header(self, sample):
  372.         rdr = reader(StringIO(sample), self.sniff(sample))
  373.         header = rdr.next()
  374.         columns = len(header)
  375.         columnTypes = { }
  376.         for i in range(columns):
  377.             columnTypes[i] = None
  378.         
  379.         checked = 0
  380.         for row in rdr:
  381.             if checked > 20:
  382.                 break
  383.             
  384.             checked += 1
  385.             if len(row) != columns:
  386.                 continue
  387.             
  388.             for col in columnTypes.keys():
  389.                 for thisType in [
  390.                     int,
  391.                     long,
  392.                     float,
  393.                     complex]:
  394.                     
  395.                     try:
  396.                         thisType(row[col])
  397.                     continue
  398.                     except (ValueError, OverflowError):
  399.                         continue
  400.                     
  401.  
  402.                 else:
  403.                     thisType = len(row[col])
  404.                 if thisType == long:
  405.                     thisType = int
  406.                 
  407.                 if thisType != columnTypes[col]:
  408.                     if columnTypes[col] is None:
  409.                         columnTypes[col] = thisType
  410.                     else:
  411.                         del columnTypes[col]
  412.                 columnTypes[col] is None
  413.             
  414.         
  415.         hasHeader = 0
  416.         for col, colType in columnTypes.items():
  417.             if type(colType) == type(0):
  418.                 if len(header[col]) != colType:
  419.                     hasHeader += 1
  420.                 else:
  421.                     hasHeader -= 1
  422.             len(header[col]) != colType
  423.             
  424.             try:
  425.                 colType(header[col])
  426.             except (ValueError, TypeError):
  427.                 hasHeader += 1
  428.                 continue
  429.  
  430.             hasHeader -= 1
  431.         
  432.         return hasHeader > 0
  433.  
  434.  
  435.